package com.vegetable.modules.service.bank.convert;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vegetable.modules.entity.bank.vo.HNNX;
import com.vegetable.modules.entity.bank.vo.HNNXTran;
import com.vegetable.modules.entity.bank.vo.StandardizedBank;
import com.vegetable.modules.entity.bank.vo.StandardizedBankTran;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HNNXConverter {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public String convert(String json) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        HNNX hnnx = mapper.readValue(json, HNNX.class);
        StandardizedBank standardizedBank = new StandardizedBank();

        standardizedBank.setAccountName(hnnx.getAccountName());
        standardizedBank.setCardNumber(hnnx.getAccountNo());
        standardizedBank.setIdNumber(null); // No direct mapping in the provided DTOs

        String[] dateRange = hnnx.getTransDetailPeriod().split("-");
        standardizedBank.setStartDate(formatDate(dateRange[0]));
        standardizedBank.setEndDate(formatDate(dateRange[1]));

        standardizedBank.setPrintTime(formatDateTime(hnnx.getGenerationTime()));

        List<StandardizedBankTran> standardizedBankTrans = new ArrayList<>();
        for (HNNXTran hnnxTran : hnnx.getHnnxTrans()) {
            StandardizedBankTran standardizedBankTran = new StandardizedBankTran();
            standardizedBankTran.setTranDate(formatDate("yyyyMMdd",hnnxTran.getTranDate()));
//            standardizedBankTran.setTranTime("00:00:00"); // No time information available
            standardizedBankTran.setCurrency(hnnx.getCurrency());
            standardizedBankTran.setAmount(formatAmount(hnnxTran.getRevenueExpenditureType(), hnnxTran.getTranAmt()));
            standardizedBankTran.setBalance(hnnxTran.getBalance());
            standardizedBankTran.setTranName(hnnxTran.getSummary());
            standardizedBankTran.setChannel(null); // No direct mapping in the provided DTOs
            standardizedBankTran.setPostscript(null); // No direct mapping in the provided DTOs
            standardizedBankTran.setCounterpartInfo(mergeCounterpartyInfo(hnnxTran));
            standardizedBankTrans.add(standardizedBankTran);
        }
        standardizedBank.setStandardizedBankTrans(standardizedBankTrans);

        return mapper.writeValueAsString(standardizedBank);
    }

    private String formatDate(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        try {
            Date date = sdf.parse(dateStr);
            return new SimpleDateFormat(DATE_FORMAT).format(date);
        } catch (ParseException e) {
            throw new RuntimeException("Error parsing date: " + dateStr, e);
        }
    }

    private String formatDate(String inputFormat, String dateStr) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputFormat);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT);

        LocalDate date = LocalDate.parse(dateStr, inputFormatter);
        return date.format(outputFormatter);
    }

    private String formatDateTime(String dateTimeStr) {
        if (StringUtils.isEmpty(dateTimeStr)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        try {
            Date date = sdf.parse(dateTimeStr);
            return new SimpleDateFormat(DATETIME_FORMAT).format(date);
        } catch (ParseException e) {
            throw new RuntimeException("Error parsing datetime: " + dateTimeStr, e);
        }
    }

    private String formatAmount(String revenueExpenditureType, String amount) {
        if ("支出".equals(revenueExpenditureType)) {
            return "-" + amount;
        }
        return amount;
    }

    private String mergeCounterpartyInfo(HNNXTran hnnxTran) {
        return hnnxTran.getCounterPartyAccountName() + "/" + hnnxTran.getPaymentReceiptAccount();
    }

    public static void main(String[] args) throws JsonProcessingException {
        HNNXConverter converter = new HNNXConverter();
        String json = "{\"币种\":\"人民币\",\"账号\":\"621****************\",\"户名\":\"**\",\"起止日期\":\"2018.11.9-2023.11.9\",\"生成时间\":\"2023.11.9 11:33:58\",\"交易明细\":[{\"序号\":\"1\",\"交易日期\":\"20231101\",\"收支类型\":\"支出\",\"摘要\":\"个账**\",\"交易金额\":\"68.85\",\"账户余额\":\"6282.79\",\"对方户名\":\"海南省******\",\"对方账户\":\"460010**********0157\"},{\"序号\":\"2\",\"交易日期\":\"20231101\",\"收支类型\":\"支出\",\"摘要\":\"个账**\",\"交易金额\":\"182.99\",\"账户余额\":\"6351.64\",\"对方户名\":\"海南省******\",\"对方账户\":\"460010**********0157\"}]}";
        String standardizedJson = converter.convert(json);
        System.out.println(standardizedJson);
    }
}
